@using DaoHang.Services
@using DaoHang.Models
@inject IWebsiteService WebsiteService
@inject ICategoryService CategoryService
@inject IWebsiteInfoService WebsiteInfoService
@inject IAliCloudAIService AliCloudAIService
@inject IJSRuntime JSRuntime

<!-- 网站管理 -->
<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">
            <i class="bi bi-globe me-2"></i>网站管理
        </h5>
        <button class="btn btn-primary btn-sm" @onclick="ShowAddWebsiteModal">
            <i class="bi bi-plus-lg me-1"></i>添加网站
        </button>
    </div>
    <div class="card-body">
        @if (isLoadingWebsites)
        {
            <div class="text-center py-4">
                <div class="spinner-border text-primary" role="status"></div>
                <p class="mt-2">加载中...</p>
            </div>
        }
        else if (websites.Any())
        {
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>图标</th>
                            <th>网站名称</th>
                            <th>URL</th>
                            <th>分类</th>
                            <th>排序</th>
                            <th>创建时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach (var website in websites)
                        {
                            <tr>
                                <td>
                                    @if (!string.IsNullOrEmpty(website.IconUrl))
                                    {
                                        <img src="@website.IconUrl" alt="@website.Name" 
                                             style="width: 24px; height: 24px; object-fit: contain;" />
                                    }
                                    else
                                    {
                                        <i class="bi bi-globe text-muted"></i>
                                    }
                                </td>
                                <td>@website.Name</td>
                                <td>
                                    <a href="@website.Url" target="_blank" class="text-decoration-none">
                                        @(website.Url.Length > 50 ? website.Url.Substring(0, 50) + "..." : website.Url)
                                    </a>
                                </td>
                                <td>
                                    <span class="badge bg-secondary">@website.Category.Name</span>
                                </td>
                                <td>@website.SortOrder</td>
                                <td>@website.CreateTime.ToString("yyyy-MM-dd")</td>
                                <td>
                                    <div class="btn-group btn-group-sm">
                                        <button class="btn btn-outline-primary" 
                                                @onclick="() => EditWebsite(website)">
                                            <i class="bi bi-pencil"></i>
                                        </button>
                                        <button class="btn btn-outline-danger" 
                                                @onclick="() => DeleteWebsite(website.Id)">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        }
                    </tbody>
                </table>
            </div>
        }
        else
        {
            <div class="text-center py-4 text-muted">
                <i class="bi bi-inbox display-4"></i>
                <p class="mt-2">暂无网站数据</p>
            </div>
        }
    </div>
</div>

<!-- 添加/编辑网站模态框 -->
<div class="modal fade" id="websiteModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    @(isEditingWebsite ? "编辑网站" : "添加网站")
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <!-- URL输入区域 -->
                    <div class="col-md-12 mb-4">
                        <div class="card border-primary">
                            <div class="card-header bg-primary text-white">
                                <h6 class="mb-0"><i class="bi bi-link-45deg me-2"></i>网站地址</h6>
                            </div>
                            <div class="card-body">
                                <div class="input-group mb-3">
                                    <span class="input-group-text"><i class="bi bi-globe"></i></span>
                                    <input type="url" class="form-control" placeholder="请输入网站URL，如：https://www.example.com" 
                                           @bind="currentWebsite.Url" required />
                                    <button class="btn btn-success" type="button" @onclick="GetWebsiteInfo" disabled="@isGettingInfo">
                                        @if (isGettingInfo)
                                        {
                                            <span class="spinner-border spinner-border-sm me-1"></span>
                                            <span>获取中...</span>
                                        }
                                        else
                                        {
                                            <i class="bi bi-download me-1"></i>
                                            <span>一键获取信息</span>
                                        }
                                    </button>
                                </div>
                                <small class="text-muted">
                                    <i class="bi bi-info-circle me-1"></i>
                                    点击"一键获取信息"可自动填充网站名称、描述和图标
                                </small>
                            </div>
                        </div>
                    </div>

                    <!-- 基本信息区域 -->
                    <div class="col-md-6 mb-4">
                        <div class="card border-info">
                            <div class="card-header bg-info text-white">
                                <h6 class="mb-0"><i class="bi bi-info-square me-2"></i>基本信息</h6>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <label class="form-label">网站名称 <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" @bind="currentWebsite.Name" required />
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">网站图标URL</label>
                                    <div class="input-group">
                                        <input type="url" class="form-control" @bind="currentWebsite.IconUrl" />
                                        @if (!string.IsNullOrEmpty(currentWebsite.IconUrl))
                                        {
                                            <span class="input-group-text">
                                                <img src="@currentWebsite.IconUrl" alt="图标预览" 
                                                     style="width: 20px; height: 20px; object-fit: contain;" 
                                                     onerror="this.style.display='none';" />
                                            </span>
                                        }
                                    </div>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">分类 <span class="text-danger">*</span></label>
                                    <select class="form-select" @bind="currentWebsite.CategoryId" required>
                                        <option value="0">请选择分类</option>
                                        @foreach (var category in categories)
                                        {
                                            <option value="@category.Id">@category.Name</option>
                                        }
                                    </select>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">排序权重</label>
                                    <input type="number" class="form-control" @bind="currentWebsite.SortOrder" min="0" />
                                    <small class="text-muted">数字越小排序越靠前</small>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 描述信息区域 -->
                    <div class="col-md-6 mb-4">
                        <div class="card border-warning">
                            <div class="card-header bg-warning text-dark">
                                <h6 class="mb-0"><i class="bi bi-chat-quote me-2"></i>描述信息</h6>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <label class="form-label">网站描述</label>
                                    <textarea class="form-control" rows="4" @bind="currentWebsite.Description" 
                                              placeholder="简要描述网站的功能和特色..."></textarea>
                                </div>

                                <div class="d-grid gap-2">
                                    <button class="btn btn-outline-info" @onclick="GenerateAISummary" disabled="@isGeneratingAI">
                                        @if (isGeneratingAI)
                                        {
                                            <span class="spinner-border spinner-border-sm me-1"></span>
                                            <span>AI生成中...</span>
                                        }
                                        else
                                        {
                                            <i class="bi bi-robot me-1"></i>
                                            <span>AI智能总结</span>
                                        }
                                    </button>
                                </div>

                                @if (!string.IsNullOrEmpty(aiGeneratedSummary))
                                {
                                    <div class="mt-3">
                                        <label class="form-label text-success">AI生成的描述：</label>
                                        <div class="card bg-light">
                                            <div class="card-body">
                                                <p class="mb-2">@aiGeneratedSummary</p>
                                                <button class="btn btn-sm btn-success" @onclick="ApplyAISummary">
                                                    <i class="bi bi-check-lg me-1"></i>应用此描述
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                }
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" @onclick="SaveWebsite" disabled="@isSaving">
                    @if (isSaving)
                    {
                        <span class="spinner-border spinner-border-sm me-1"></span>
                        <span>保存中...</span>
                    }
                    else
                    {
                        <i class="bi bi-check-lg me-1"></i>
                        <span>保存</span>
                    }
                </button>
            </div>
        </div>
    </div>
</div>

@code {
    /// <summary>
    /// 网站列表
    /// </summary>
    [Parameter] public List<Website> websites { get; set; } = new();
    
    /// <summary>
    /// 分类列表
    /// </summary>
    [Parameter] public List<Category> categories { get; set; } = new();
    
    /// <summary>
    /// 数据变更通知回调
    /// </summary>
    [Parameter] public EventCallback OnDataChanged { get; set; }

    // 状态变量
    private bool isLoadingWebsites = false;
    private bool isEditingWebsite = false;
    private bool isGettingInfo = false;
    private bool isGeneratingAI = false;
    private bool isSaving = false;
    
    // 当前编辑的网站
    private Website currentWebsite = new();
    private string aiGeneratedSummary = string.Empty;

    /// <summary>
    /// 显示添加网站模态框
    /// </summary>
    public async Task ShowAddWebsiteModal()
    {
        isEditingWebsite = false;
        currentWebsite = new Website { SortOrder = websites.Count + 1 };
        aiGeneratedSummary = string.Empty;
        await JSRuntime.InvokeVoidAsync("showModal", "websiteModal");
    }

    /// <summary>
    /// 编辑网站
    /// </summary>
    /// <param name="website">要编辑的网站</param>
    public async Task EditWebsite(Website website)
    {
        isEditingWebsite = true;
        currentWebsite = new Website
        {
            Id = website.Id,
            Name = website.Name,
            Url = website.Url,
            Description = website.Description,
            IconUrl = website.IconUrl,
            CategoryId = website.CategoryId,
            SortOrder = website.SortOrder,
            CreateTime = website.CreateTime
        };
        aiGeneratedSummary = string.Empty;
        await JSRuntime.InvokeVoidAsync("showModal", "websiteModal");
    }

    /// <summary>
    /// 获取网站信息
    /// </summary>
    private async Task GetWebsiteInfo()
    {
        if (string.IsNullOrEmpty(currentWebsite.Url))
        {
            await JSRuntime.InvokeVoidAsync("alert", "请先输入网站URL");
            return;
        }

        isGettingInfo = true;
        try
        {
            var websiteInfo = await WebsiteInfoService.GetWebsiteInfoAsync(currentWebsite.Url);
            if (websiteInfo != null)
            {
                if (string.IsNullOrEmpty(currentWebsite.Name))
                    currentWebsite.Name = websiteInfo.Title ?? "";
                if (string.IsNullOrEmpty(currentWebsite.Description))
                    currentWebsite.Description = websiteInfo.Description ?? "";
                if (string.IsNullOrEmpty(currentWebsite.IconUrl))
                    currentWebsite.IconUrl = websiteInfo.IconUrl ?? "";
                
                StateHasChanged();
            }
        }
        catch (Exception ex)
        {
            await JSRuntime.InvokeVoidAsync("alert", $"获取网站信息失败：{ex.Message}");
        }
        finally
        {
            isGettingInfo = false;
        }
    }

    /// <summary>
    /// 生成AI摘要
    /// </summary>
    private async Task GenerateAISummary()
    {
        if (string.IsNullOrEmpty(currentWebsite.Url))
        {
            await JSRuntime.InvokeVoidAsync("alert", "请先输入网站URL");
            return;
        }

        isGeneratingAI = true;
        try
        {
            aiGeneratedSummary = await AliCloudAIService.GenerateSummaryAsync("", currentWebsite.Url);
            StateHasChanged();
        }
        catch (Exception ex)
        {
            await JSRuntime.InvokeVoidAsync("alert", $"AI生成失败：{ex.Message}");
        }
        finally
        {
            isGeneratingAI = false;
        }
    }

    /// <summary>
    /// 应用AI生成的描述
    /// </summary>
    private void ApplyAISummary()
    {
        currentWebsite.Description = aiGeneratedSummary;
        aiGeneratedSummary = string.Empty;
        StateHasChanged();
    }

    /// <summary>
    /// 保存网站
    /// </summary>
    private async Task SaveWebsite()
    {
        if (string.IsNullOrEmpty(currentWebsite.Name) || 
            string.IsNullOrEmpty(currentWebsite.Url) || 
            currentWebsite.CategoryId == 0)
        {
            await JSRuntime.InvokeVoidAsync("alert", "请填写必填字段（网站名称、URL、分类）");
            return;
        }

        isSaving = true;
        try
        {
            if (isEditingWebsite)
            {
                await WebsiteService.UpdateWebsiteAsync(currentWebsite);
            }
            else
            {
                await WebsiteService.CreateWebsiteAsync(currentWebsite);
            }

            await JSRuntime.InvokeVoidAsync("hideModal", "websiteModal");
            await OnDataChanged.InvokeAsync();
        }
        catch (Exception ex)
        {
            await JSRuntime.InvokeVoidAsync("alert", $"保存失败：{ex.Message}");
        }
        finally
        {
            isSaving = false;
        }
    }

    /// <summary>
    /// 删除网站
    /// </summary>
    /// <param name="websiteId">网站ID</param>
    public async Task DeleteWebsite(int websiteId)
    {
        var confirmed = await JSRuntime.InvokeAsync<bool>("confirm", "确定要删除这个网站吗？");
        if (!confirmed) return;

        try
        {
            await WebsiteService.DeleteWebsiteAsync(websiteId);
            await OnDataChanged.InvokeAsync();
        }
        catch (Exception ex)
        {
            await JSRuntime.InvokeVoidAsync("alert", $"删除失败：{ex.Message}");
        }
    }
} 